<?php
class model_var extends common_model {
	/**
	 * 基本表属性
	 */
	protected $table = 'var';
	protected $pk = 'var_id';
	
	/**
	 * 获取变量值
	 * @param string $key
	 */
	public function get($key) {
		$res = $this->find("`key`='$key'", 'var_id DESC', 1);
		return empty($res) ? null : $res['value'];
	}

	/**
	 * 获取变量值
	 * @param string $key
	 */
	public function set($key, $value) {
		$ret = $this->update_by_conditions(array('value' => $value), "`key`='$key'");

        if ($this->db->affected_rows() === 0)
        {
            $ret = $this->find("`key`='$key'", 1);

            if (!$ret)
            {
                $ret = $this->create(array('value' => $value, 'key' => $key));
            }
        }

        return $ret;
	}
	
	/**
	 * 获取变量数组
	 * @param string $key
	 */
	public function get_all($key) {
		$res = $this->find_all("`key`='$key'", '`key`');
		
		if(empty($res)) {
			return null;
		} else {
			$values = array();
			foreach ($res as $row) {
				$values[] = $row['value'];
			}
			return $values;
		}
	}
	
}
